package com.hoopchina.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

public class ImageDispose {

	/**
	 * 把bitmap转为二进制数组
	 */
	public static byte[] getBitmapByte(Bitmap bitmap) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
		try {
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return out.toByteArray();
	}

	/**
	 * 把二进制数组转为bitmap
	 */
	public static Bitmap getBitmapFromByte(byte[] temp) {
		Bitmap rawBitmap=null;
		if (temp != null) {
			rawBitmap=  BitmapFactory.decodeByteArray(temp, 0, temp.length);
		} 
		return rawBitmap;
	}

	/**
	 * 把bitmap转为drawable
	 */
	public static Drawable getDrawableFromBitmap(Bitmap bitmap) {
		return new BitmapDrawable(bitmap);
	}

	/**
	 * 对bitmap进行缩放
	 */
	public static Bitmap getSmallBitmap(Bitmap oldMap, int w, int h) {
		Bitmap newmap = Bitmap.createScaledBitmap(oldMap, w, h, true);
		return newmap;
	}

	/**
	 * 对过大的图片进行缩放
	 */
	public static byte[] changeBigPicSize(byte[] picByte, int pixWidth) {
		Bitmap rawBitmap = getBitmapFromByte(picByte);
		Drawable oldDrawable=getDrawableFromBitmap(rawBitmap);
		byte[] newPicByte=null;
		int width=oldDrawable.getIntrinsicWidth();
		int height=oldDrawable.getIntrinsicHeight();
		
		if (width > pixWidth) {
			int picRealWidth = pixWidth;
			int picRealHeight = (int) (height * (pixWidth * 1.0 / width));
			Bitmap newBitmap = getSmallBitmap(rawBitmap, picRealWidth,picRealHeight);
			newPicByte = getBitmapByte(newBitmap);
			rawBitmap.recycle();
		}
		return newPicByte;
	}
	
}
